<template>
	<view class="pd10_15">
		<view class="pd10_15" @tap="showinfo()">{{$t('vip.tip4')}}</view>
		<view class="flex wrap space">
			<view v-for="(item,index) in viplist" :key="index" :class="selid==item.id?'selected':''" class="box pd20_15 item" 
			@tap="changeNum(index)">
				<view class="ft14 num">{{item.num}}{{item.numtype}} VIP</view>
				<view class="ft12 price"><text class="ft24">{{item.price}}</text>{{item.currency}}</view>
				<view class="ft12 text">{{$t('Recharge tip')}}</view>
			</view>
		</view>
		<view class="box mt16 pd16_15">
			<view class="ft16 pb16 ftw600 cl-main">{{$t('Payment')}}</view>
			<radio-group @change="changeType">
				<block v-for="(item,index) in payTypes" :key="index">
				<view v-if="item.open==1" class="pt16 pb16 flex alcenter space bdtop">
					<view class="flex alcenter">
						<text class="iconfont iconicon_arrow_circle ft20" style="color: #55aaff;"></text>
						<text class="ml15 ft14 ftw500 cl-main">{{item.title}}</text>
					</view>
					<view>
						<radio :value="item.name" :checked="payType == item.name" :disabled="false" :color="tempColor"  />
					</view>
				</view>
				</block>
			</radio-group>
		</view>
		<view class="form-footer-h form-footer">
			<view class="form-footer-main pd10_15 flex">
				<button  @click="paykami" class="btn-big">{{$t('Cryptocard')}}</button>
				<button  @click="paySuccess" :style="getBtnStyle" :loading="loading" class="btn-big">{{$t('Pay Now')}}</button>
			</view>
		</view>
		<view style="margin-bottom: 150rpx;"></view>
		<pop
		    ref="infopop"
		    direction="center" 
		    :is_close="true" 
		    :is_mask="true" 
		    :width="90"  
		    height="fit-content" 
		    :maskFun="false" 
		>
		<scroll-view class="mt16 box" scroll-y="true" style="height:800rpx;">
			<view class="pd10_15">
				<rich-text :nodes="tiptext"></rich-text>
			</view>
		</scroll-view>
		</pop>
		<hFormAlert v-if="cancelShow" 
		:title="this.$t('Exchange membership')"
		name="cancel_desc" 
		:placeholder="this.$t('Please enter the card number')" 
		@confirm="confirm" 
		@cancel="cancel" 
		:confirmText="this.$t('OK')"
		:cancelText="this.$t('Cancel')"></hFormAlert>
	</view>
</template>

<script>
	import {
	    Iap,
	    IapTransactionState
	  } from "@/common/iap.js"
	import hFormAlert from '@/components/h-form-alert/h-form-alert.vue';
	import pop from "@/components/ming-pop/ming-pop.vue";
	let timer = null;
	export default{
		components: {hFormAlert,pop},
		data(){
			return {
				selid:0,
				viplist:[],
				cancelShow:false,
				payid:0,
				tiptext:'',
				loading: false,
				productId: "",//苹果内购产品id
				products:[],//VIP所有的虚拟id
				productList: [],
				payTypes:[],
				payType:'wxpay',
				useiap:false,//是否使用苹果内购
				currency:'USD',
				drama_id:0,
				video_id:0
			}
		},
		onLoad(e){
			//视频来源
			if(e.vid){
				this.drama_id = e.vid
			}
			if(e.mid){
				this.video_id = e.mid
			}
			this.getvip()
			this.artinfo()
			this.payid=uni.getStorageSync("payid")
			if(this.payid>0){
				timer = setInterval(() => {
					this.checkpay(this.payid)
				}, 1000);
			}
			//判断支付方式开始
			let payTypes = uni.getStorageSync("config").paytypes;
			// #ifdef H5
			//公众号里不能用支付宝
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger'){
				for (var i = 0; i < payTypes.length; i++) {
					if(payTypes[i].name=='alipay'){
						payTypes[i].open=0;
					}
				}
			}
			// #endif

			this.payTypes = payTypes;
			for (var i = 0; i < payTypes.length; i++) {
				if(payTypes[i].open ==1){
					this.payType = payTypes[i].name
					break;
				}
			}
		},
		onShow() {
			uni.setNavigationBarTitle({
			    title: this.$t('Activate membership')
			});
		},
		methods:{
			async artinfo(){
				let data = {type:'vip'};
				let [err,res] =await this.$httpas.get('/api/index/artinfo',data);
				if(res.data.code == 1){
					this.tiptext = res.data.data.content
				}
			},
			showinfo(){
				this.$refs.infopop.show();
			},
			changeType(e){
				this.payType = e.detail.value;
			},
			changeNum(index){
				let selid = this.viplist[index].id
				let vpid = this.viplist[index].vpid
				let price = this.viplist[index].price
				
				this.selid = parseInt(selid);
				this.productId = vpid;
				this.goodsPrice = price*100
				this.currency = this.viplist[index].currency
			},
			async getvip(){
				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				let [err,res] =await this.$httpas.get('/api/user/viplist',data);
				if(res.data.code==1){
					this.viplist =res.data.data
					//虚拟支付产品列表
					for (var i = 0; i < this.viplist.length; i++) {
						this.products.push(this.viplist[i].vpid)
					}
					this.changeNum(0)
					// #ifdef APP-PLUS
					//苹果内支付
					if(uni.getSystemInfoSync().osName=="ios"){
						this._iap = new Iap({
							products: this.products // 苹果开发者中心创建
						})
						this.init();
					}
					// #endif
				}
			},
			paySuccess(){
				if(this.viplist.length==0 || this.payTypes.length==0){
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Operation failed'),
						showCancel: false
					});
					return false;
				}
				//#ifdef H5
				this.payH5()
				//#endif
				
				// #ifdef APP-PLUS
				if(uni.getSystemInfoSync().osName=="ios" && this.useiap == true){
					this.payapple()
				}else{
					if(this.payType=='wxpay'){
						uni.showModal({
							title: this.$t('Warning'),
							content: this.$t('Operation failed'),
							showCancel: false
						});
						return false;
					}else{
						this.payH5()
					}
				}
				//#endif
			},
			async payH5(){
				if(!this.selid){
					uni.showToast({ title:this.$t('Please select a recharge product'),icon:"none" });
					return false
				}
				uni.showLoading({
				    title: this.$t('Loading')
				});

				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				data.id = this.selid;
				data.actype='vip'
				data.paytype = this.payType;
				data.platform = 'h5'
				data.currency = this.currency
				data.drama_id = this.drama_id
				data.video_id = this.video_id
				// #ifdef H5
				var ua = window.navigator.userAgent.toLowerCase();
				if(ua.match(/MicroMessenger/i) == 'micromessenger'){
					data.platform = 'wxgzh';
				}
				// #endif
				let [err,res] =await this.$httpas.post('/api/pay/recharge',data);
				if(res.data.code==1){
					uni.hideLoading();
					
					// #ifdef APP-PLUS  
					uni.navigateTo({
						url:'/pages/client/webva?url='+res.data.data.payurl
					})
					// #endif  
					// #ifdef H5
					window.location.href=res.data.data.payurl
					// #endif
					//监控支付
					if(data.platform == 'wxgzh'){
						uni.setStorageSync('payid', res.data.data.payid);
					}
				}else{
					uni.hideLoading();
					uni.showToast({ title: res.data.msg,icon:"none" });
				}
			},
			checkpay(payid){
				let data = {'payid':payid};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				uni.request({
					url: this.configs.webUrl+'/api/pay/checkpay',
					data: data,
					success: res =>{
						if(res.data.code==1){
							if(res.data.data==2){
								if (timer) {
									clearInterval(timer);
									timer = null;
								}
								uni.removeStorageSync('payid');
								uni.switchTab({
									url: '/pages/client/member/index'
								});
							}
						}
					}
				});
			},
			async init() {//初始化苹果内支付
							uni.showLoading({
							  title: this.$t('Loading'),
							});
								
							try {
							  // 初始化，获取iap支付通道
							  await this._iap.init();
								
							  // 从苹果服务器获取产品列表
							  this.productList = await this._iap.getProduct();
							  this.productId = this.productList[0].productid;
							  //console.log(this.productList)
							} catch (e) {
							  uni.showModal({
								title: this.$t('Warning'),
								content: this.$t('Pay failed'),
								showCancel: false
							  });
							} finally {
							  uni.hideLoading();
							}
								
							if (this._iap._ready) {
							  this.restore();
							}
						  },
						  async restore() {
							// 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
							try {
							  // 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
							  const transactions = await this._iap.restoreCompletedTransactions({
								username: ""
							  });
							  if (!transactions.length) {
								return;
							  }
							  for (let i = 0; i < transactions.length; i++) {
								  let transaction= transactions[i]
								  //console.log(transaction)
								  switch (transaction.transactionState) {
									case IapTransactionState.purchased:
									  // 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
									  let result = await this.validatePaymentResult({
										 orderId: transaction.payment.username,
										 transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
										 transactionIdentifier: transaction.transactionIdentifier
									   });
									  // 验证通过，交易结束，关闭订单
										if (result) {
											await this._iap.finishTransaction(transaction);
										}
									  break;
									case IapTransactionState.failed:
									  // 关闭未支付的订单
									  await this._iap.finishTransaction(transaction);
									  break;
									default:
									  break;
								  }
							  }
							} catch (e) {
							  uni.showModal({
								content: e.message,
								showCancel: false
							  });
							}
						},
						async payapple() {
							if (this.loading == true) {
							  return;
							}
							this.loading = true;
					
							uni.showLoading({
							  title: this.$t('Loading')
							});
					
							try {
							  // 从开发者服务器创建订单
							  const orderId = await this.createOrder();
					
							  // 请求苹果支付
							  const transaction = await this._iap.requestPayment({
								productid: this.productId,
								manualFinishTransaction: true,
								username: orderId //根据业务需求透传参数，关联用户和订单关系
							  });
							//console.log(transaction)
							  // 在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
							  let result = await this.validatePaymentResult({
							     orderId: orderId,
							     transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
							     transactionIdentifier: transaction.transactionIdentifier
							   });
					
							  // 验证成功后关闭订单
							  if (result) {
							  	await this._iap.finishTransaction(transaction);
							  }
							  // 支付成功
							  uni.showModal({
							  	title: this.$t('Warning'),
							  	content: this.$t('Pay success'),
							  	showCancel: false,
							  	confirmText: this.$t('OK'),
							  	success: function (res) {
							  		if (res.confirm) {
							  			uni.navigateBack();
							  		}
							  	}
							  });
							} catch (e) {
							  uni.showModal({
								content: this.$t('Pay failed'),
								showCancel: false
							  });
							} finally {
							  this.loading = false;
							  uni.hideLoading();
							}
			},
			createOrder() {//创建苹果内购订单
				return new Promise((resolve, reject) => {
					let data = {};
					data.token = uni.getStorageSync("userinfo").token;
					data.uid = uni.getStorageSync("userinfo").id;
					data.id = this.selid;
					data.actype='vip'
					data.paytype ='appleiap'
					data.currency = this.currency
					data.drama_id = this.drama_id
					data.video_id = this.video_id
					uni.request({
						url: this.configs.webUrl+'/api/pay/recharge',
						data: data,
						header:{'site':this.configs.subsite},
						success: res =>{
							if(res.data.code==1){
								resolve(res.data.data.out_trade_no)
							}else{
								reject(res.data.msg)
							}
						}
					});
				})
			},
			validatePaymentResult(data) {//验证苹果内购订单
						return new Promise((resolve, reject) => {
							uni.request({
								url: this.configs.webUrl+'/index/pay/notify_iap',
								data: data,
								success: res =>{
									if(res){
										resolve(1)
									}else{
										reject(0)
									}
								}
							});
						});
			},
			paykami(){
				this.cancelShow=true
			},
			cancel(){
				this.cancelShow=false
			},
			async confirm(e){
				if(!e.kamiNo){
					this.cancelShow=false
					uni.showToast({ title: this.$t('Please enter the card number'),icon:"none" });
					return false
				}
				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				data.kamiNo = e.kamiNo;
				let [err,res] =await this.$httpas.post('/api/user/kami',data);
				if(res.data.code==1){
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Pay success'),
						showCancel: false,
						confirmText: this.$t('OK'),
						success: function (res) {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
				}else{
					uni.showToast({ title: res.data.msg,icon:"none" });
				}
				this.cancelShow=false
			}
		}
	}
</script>

<style>
	.item{width: 300rpx; text-align: center;margin: 20rpx;border: solid 1px #cccccc;}
	.selected{background-color: bisque;border: solid 1px orange;}
	.item .num{margin: 30rpx 0;}
	.item .price{color: orange;margin: 30rpx 0;}
	.item .text{color: #999999;}
</style>